const { default: axios } = require('axios');
const { getSqlLiteData } = require('../../SqlLiteDB');

module.exports = function setWorkCollectionRouter (router) {

    //查询采集记录
    router.get('/getWorkCollections', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.query['dataContent']);
            let prosn = dataContent.prosn;
            let SqlString = 'SELECT T.*,F.filenames FROM TASKCARD T' +
                ' LEFT JOIN TASKCARD_FILES F ON T.prosn = F.prosn' +
                ' AND T.worprocedureid = F.worprocedureid' +
                ' AND T.orderindex = F.orderindex' +
                (prosn ? ` WHERE T.prosn='${prosn}` : '');
            let procedures = await getSqlLiteData(SqlString);

            res.status(200).json({
                procedures,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    //新增采集记录
    router.post('/insertWorkCollection', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.body['dataContent']);
            let collection = dataContent.collection;

            let SqlString = `INSERT INTO TASKCARD(prosn,worprocedureid,wpid,wpname,wpresult,workid,collect_time) 
            VALUES ('${collection.prosn}','${collection.worprocedureid}', '${collection.wpid}', '${collection.wpname}',
                 '${collection.wpresult}','${collection.workid}','${collection.collect_time}')`;
            let result = await getSqlLiteData(SqlString);

            res.status(200).json({
                result,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    //新增采集记录
    router.post('/checkAndInsertWorkCollection', async function (req, res, next) {
        try {
            let result = {
                isAllSuccess: false,
                insertTaskcardResult: '',
                isInsertTaskcardSuccess: false,
                uploadFilesResult: [],
                isUploadFilesSuccess: false,
                insertTaskcardFilesResult: '',
                isInsertTaskcardFilesSuccess: false,
            };
            let dataContent = JSON.parse(req.body['dataContent']);
            let collection = dataContent.collection;

            //先查流水号有没有排产
            let SqlString1 = `select * from jm_woschedule W JOIN jm_workorder JM ON W.jm_workorderid=JM.jm_workorderid AND JM.wostate=1 WHERE W.prosn='${collection.prosn}'`;
            let result1 = await getSqlLiteData(SqlString1);
            if (result1.length > 0) {
                let SqlString2 = `SELECT w.prosn,
  m.orderindex,
  wp.*,
  t.prosn as prosn1,
  t.worprocedureid as worprocedureid1,
  t.orderindex as orderindex1 
  FROM jm_woschedule w 
  join matworkprocedure m on w.matcode=m.matcode 
  join workprocedure wp on m.worprocedureid = wp.worprocedureid 
  left join taskcard t on w.prosn=t.prosn AND m.orderindex=t.orderindex 
  WHERE w.prosn='${collection.prosn}'`;
                let result2 = await getSqlLiteData(SqlString2);
                let nextWp = result2.find(item => !item.prosn1);
                if (nextWp) {
                    if (nextWp.worprocedureid == collection.worprocedureid) {
                        let SqlString = `INSERT INTO TASKCARD(prosn,worprocedureid,orderindex,wpid,wpname,wpresult,workid,collect_time) 
                            VALUES ('${collection.prosn}','${collection.worprocedureid}','${nextWp.orderindex}', '${collection.wpid}', '${collection.wpname}',
                            '${collection.wpresult}','${collection.workid}','${collection.collect_time}')`;
                        result.insertTaskcardResult = await getSqlLiteData(SqlString);

                        if (result.insertTaskcardResult.includes('成功')) {
                            result.isInsertTaskcardSuccess = true;

                            if (collection.files.length > 0) {
                                let filenames = '';
                                for (let i = 0; i < collection.files.length; i++) {
                                    let file = collection.files[i];
                                    file.path = `./public/collectionFiles/${collection.prosn}/${collection.worprocedureid}/${nextWp.orderindex}/` + file.filename;
                                    filenames += ';' + file.filename;
                                }
                                filenames = filenames.slice(1);

                                let paramData = {
                                    files: collection.files,
                                };
                                let fileUploadResult = await axios.post('http://127.0.0.1:14603/supplier/uploadFiles', { dataContent: JSON.stringify(paramData) });
                                result.uploadFilesResult = Array.from(fileUploadResult.data.result);

                                if (result.uploadFilesResult.length > 0 && result.uploadFilesResult.every(resultStr => resultStr.includes('成功'))) {
                                    result.isUploadFilesSuccess = true;

                                    let SqlString = `INSERT INTO TASKCARD_FILES(prosn,worprocedureid,orderindex,filenames) 
                            VALUES ('${collection.prosn}','${collection.worprocedureid}','${nextWp.orderindex}', '${filenames}')`;
                                    result.insertTaskcardFilesResult = await getSqlLiteData(SqlString);
                                    if (result.insertTaskcardFilesResult.includes('成功')) {
                                        result.isInsertTaskcardFilesSuccess = true;
                                        result.isAllSuccess = true;
                                    }
                                }
                                else {
                                    result.isUploadFilesSuccess = false;
                                }

                            }
                            else {
                                result.isAllSuccess = true;
                            }
                        }
                    }
                    else {
                        result.insertTaskcardResult = `失败,采集工序(${collection.wpname})与物料下一道工序(${nextWp.wpname})顺序不匹配`;
                    }
                }
                else {
                    result.insertTaskcardResult = '失败,该流水号工序已全部完成';
                }


            }
            else {
                result.insertTaskcardResult = '流水号未排产';
            }

            res.status(200).json({
                result,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    //修改采集记录
    router.post('/updateWorkCollection', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.body['dataContent']);
            let collection = dataContent.collection;

            let SqlString = `REPLACE INTO TASKCARD(prosn,worprocedureid,wpid,wpname,wpresult,workid,collect_time) 
            VALUES ('${collection.prosn}','${collection.worprocedureid}', '${collection.wpid}', '${collection.wpname}',
                 '${collection.wpresult}','${collection.workid}','${collection.collect_time}')`;
            let result = await getSqlLiteData(SqlString);

            res.status(200).json({
                result,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    //删除采集记录
    router.post('/deleteWorkCollection', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.body['dataContent']);
            let collection = dataContent.collection;
            let prosn = collection.prosn;
            let worprocedureid = collection.worprocedureid;
            let orderindex = collection.orderindex;

            let SqlString = `DELETE FROM TASKCARD WHERE prosn ='${prosn}' and worprocedureid ='${worprocedureid}' and orderindex='${orderindex}'`;
            let result = await getSqlLiteData(SqlString);

            let deleteTaskcardFilesSqlString = `DELETE FROM TASKCARD_FILES WHERE` +
                ` prosn = '${prosn}' ` +
                ` and worprocedureid = '${worprocedureid}'` +
                ` and orderindex = '${orderindex}'`;
            let deleteTaskcardFilesResult = await getSqlLiteData(deleteTaskcardFilesSqlString);
            if (deleteTaskcardFilesResult.includes('成功')) {
                console.log('TASKCARD_FILES 文件记录删除成功 :>> ', deleteTaskcardFilesResult);
            }
            else {
                console.log('TASKCARD_FILES 文件记录删除失败 :>> ', deleteTaskcardFilesResult);
            }

            let files = collection.files;
            let paramData = {
                files: [{ filePath: `/public/collectionFiles/${prosn}/${worprocedureid}/${orderindex}` }],
            };
            let fileDeleteResult = await axios.post('http://127.0.0.1:14603/supplier/deleteFiles', { dataContent: JSON.stringify(paramData) });
            let deleteFilesResult = Array.from(fileDeleteResult.data.result);
            if (deleteFilesResult.every(resultStr => resultStr.includes('成功'))) {
                console.log('删除采集记录,文件删除成功 :>> ', deleteFilesResult);
            }
            else {
                console.log('删除采集记录,文件删除失败 :>> ', deleteFilesResult);

            }

            res.status(200).json({
                result,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    //删除采集文件和文件记录
    router.post('/deleteWorkCollectionFiles', async function (req, res, next) {
        try {
            let result = {
                isAllSuccess: false,
                deleteFilesResult: [],
                isDeleteFilesSuccess: false,
                updateTaskcardFilesResult: '',
                isUpdateTaskcardFilesSuccess: false,
            };

            // 要删除的文件在req.files中
            let dataContent = JSON.parse(req.body['dataContent']);
            let files = dataContent.files;
            // 先删文件记录
            let updateResultArr = [];
            for (let i = 0; i < files.length; i++) {
                // const filename = files[i].path + pathLib.parse(files[i].originalname).ext;
                // console.log(filename);
                let file = files[i];
                let paramList = file.filePath.split('/');
                let prosn = paramList[3];
                let worprocedureid = paramList[4];
                let orderindex = paramList[5];

                let taskcardFilesSqlString = `SELECT * FROM TASKCARD_FILES WHERE` +
                    ` prosn = '${prosn}' ` +
                    ` and worprocedureid = '${worprocedureid}'` +
                    ` and orderindex = '${orderindex}'`;
                let getResult = await getSqlLiteData(taskcardFilesSqlString);
                if (getResult.length > 0) {
                    let filenamesInTable = getResult[0]['filenames'];
                    let filenameList = filenamesInTable.split(';');
                    let index = filenameList.indexOf(file.filename);
                    if (index != -1) {
                        filenameList.splice(index, 1);
                        let updateSqlString = `UPDATE TASKCARD_FILES  SET filenames='${filenameList.join(';')}' WHERE` +
                            ` prosn = '${prosn}' ` +
                            ` and worprocedureid = '${worprocedureid}'` +
                            ` and orderindex = '${orderindex}'`;
                        let updateResult = await getSqlLiteData(updateSqlString);

                        updateResultArr.push(updateResult);
                    }
                }

            }
            result.updateTaskcardFilesResult = updateResultArr;
            //再删文件
            if (result.updateTaskcardFilesResult.every(resultStr => resultStr.includes('成功'))) {
                result.isUpdateTaskcardFilesSuccess = true;
                let paramData = {
                    files: files,
                };
                let fileDeleteResult = await axios.post('http://127.0.0.1:14603/supplier/deleteFiles', { dataContent: JSON.stringify(paramData) });
                result.deleteFilesResult = Array.from(fileDeleteResult.data.result);
                if (result.deleteFilesResult.every(resultStr => resultStr.includes('成功'))) {
                    result.isDeleteFilesSuccess = true;
                    result.isAllSuccess = true;
                }
            }


            res.status(200).json({
                result: result,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });
};
